package com.bank.ui.admin;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import com.bank.dao.TransactionDAO;
import com.bank.entity.Transaction;
import javax.swing.table.DefaultTableModel;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;

public class QueryTransactionDialog extends JDialog {

    private final JTable table;
    private final JTextField cardIdField;
    private final JComboBox<String> tradeTypeComboBox;
    private final JFormattedTextField startDateField;
    private final JFormattedTextField endDateField;
    private final JTextField remarkField;
    private final JButton clearButton;
    private final JTextField tradeIdField; // 改为交易ID输入框

    public QueryTransactionDialog(JTable parentTable) {
        setTitle("交易查询");
        setSize(600, 500);
        setModal(true);
        setLocationRelativeTo(null);

        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 查询条件面板
        JPanel conditionPanel = new JPanel(new GridLayout(6, 2, 10, 10));
        conditionPanel.setBorder(BorderFactory.createTitledBorder("查询条件"));

        // 日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        conditionPanel.add(new JLabel("卡号:"));
        cardIdField = new JTextField();
        conditionPanel.add(cardIdField);

        conditionPanel.add(new JLabel("交易类型:"));
        tradeTypeComboBox = new JComboBox<>(new String[]{"全部", "存款", "取款", "转账"});
        conditionPanel.add(tradeTypeComboBox);

        conditionPanel.add(new JLabel("开始日期 (yyyy-MM-dd):"));
        startDateField = new JFormattedTextField(dateFormat);
        startDateField.setColumns(10);
        conditionPanel.add(startDateField);

        conditionPanel.add(new JLabel("结束日期 (yyyy-MM-dd):"));
        endDateField = new JFormattedTextField(dateFormat);
        endDateField.setColumns(10);
        conditionPanel.add(endDateField);

        conditionPanel.add(new JLabel("备注:"));
        remarkField = new JTextField();
        conditionPanel.add(remarkField);

        conditionPanel.add(new JLabel("交易ID:")); // 改为交易ID标签
        tradeIdField = new JTextField(); // 改为交易ID输入框
        conditionPanel.add(tradeIdField);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        JButton queryButton = new JButton("查询");
        clearButton = new JButton("清空条件");

        buttonPanel.add(queryButton);
        buttonPanel.add(clearButton);

        // 表格面板
        table = new JTable();
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBorder(BorderFactory.createTitledBorder("查询结果"));

        // 组装主界面
        mainPanel.add(conditionPanel, BorderLayout.NORTH);
        mainPanel.add(buttonPanel, BorderLayout.CENTER);
        mainPanel.add(scrollPane, BorderLayout.SOUTH);

        add(mainPanel);

        // 查询按钮事件
        queryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                queryTransactions();
            }
        });

        // 清空按钮事件
        clearButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardIdField.setText("");
                tradeTypeComboBox.setSelectedIndex(0);
                startDateField.setValue(null);
                endDateField.setValue(null);
                remarkField.setText("");
                tradeIdField.setText(""); // 清空交易ID输入框
            }
        });
    }

    private void queryTransactions() {
        String cardId = cardIdField.getText().trim();
        String tradeType = (String) tradeTypeComboBox.getSelectedItem();
        if ("全部".equals(tradeType)) {
            tradeType = null;
        }

        Date utilStartDate = null;
        Date utilEndDate = null;
        try {
            if (startDateField.getValue() != null) {
                utilStartDate = new SimpleDateFormat("yyyy-MM-dd").parse(startDateField.getText());
            }
            if (endDateField.getValue() != null) {
                utilEndDate = new SimpleDateFormat("yyyy-MM-dd").parse(endDateField.getText());

                // 结束日期设置为当天的23:59:59
                Calendar cal = Calendar.getInstance();
                cal.setTime(utilEndDate);
                cal.set(Calendar.HOUR_OF_DAY, 23);
                cal.set(Calendar.MINUTE, 59);
                cal.set(Calendar.SECOND, 59);
                utilEndDate = cal.getTime();
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "日期格式错误，请使用yyyy-MM-dd格式", "输入错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        String remark = remarkField.getText().trim();
        String tradeIdText = tradeIdField.getText().trim(); // 获取交易ID输入
        Integer tradeId = null;
        if (!tradeIdText.isEmpty()) {
            try {
                tradeId = Integer.parseInt(tradeIdText);
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "交易ID必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }

        TransactionDAO transactionDAO = new TransactionDAO();
        try {
            // 使用java.util.Date类型参数
            List<Transaction> transactions = transactionDAO.queryTransactionsByCriteria(
                    cardId.isEmpty() ? null : cardId,
                    tradeType,
                    utilStartDate,
                    utilEndDate,
                    remark.isEmpty() ? null : remark,
                    tradeId); // 传入交易ID参数

            if (transactions.isEmpty()) {
                JOptionPane.showMessageDialog(this, "未找到符合条件的交易记录", "查询结果", JOptionPane.INFORMATION_MESSAGE);
            }

            String[] columnNames = {"交易ID", "交易日期", "交易类型", "卡号", "交易金额", "备注"};
            Object[][] data = new Object[transactions.size()][columnNames.length];
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            for (int i = 0; i < transactions.size(); i++) {
                Transaction transaction = transactions.get(i);
                data[i][0] = transaction.getTradeID();
                data[i][1] = sdf.format(transaction.getTradeDate());
                data[i][2] = transaction.getTradeType();
                data[i][3] = transaction.getCardID();
                data[i][4] = String.format("%.2f", transaction.getTradeMoney());
                data[i][5] = transaction.getRemark();
            }

            DefaultTableModel model = new DefaultTableModel(data, columnNames) {
                @Override
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            };
            table.setModel(model);

            // 设置列宽
            table.getColumnModel().getColumn(0).setPreferredWidth(60);
            table.getColumnModel().getColumn(1).setPreferredWidth(140);
            table.getColumnModel().getColumn(4).setPreferredWidth(80);

        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this,
                    "查询失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}